

#include "thread.h"
#include <time.h>


int mkfilename(char *filename, int len) {
	time_t	t;
	struct tm *tm;
	char tmp[4] ={};
	memset(filename,0, len);
	t = time(0);
	tm = localtime(&t);
	if (tm->tm_mon < 10) {
		sprintf(tmp, "0%d", tm->tm_mon+1);
	} else {
		sprintf(tmp, "%d", tm->tm_mon+1);
	}
	strncat(filename,tmp,2);
	if (tm->tm_mday < 10) {
		sprintf(tmp, "0%d", tm->tm_mday);
	} else {
		sprintf(tmp, "%d", tm->tm_mday);
	}
	strncat(filename,tmp,2);
	if (tm->tm_hour < 10) {
		sprintf(tmp, "0%d", tm->tm_hour);
	} else {
		sprintf(tmp, "%d", tm->tm_hour);
	}
	strncat(filename,tmp,2);
	if (tm->tm_min < 10) {
		sprintf(tmp, "0%d", tm->tm_min);
	} else {
		sprintf(tmp, "%d", tm->tm_min);
	}
	strncat(filename,tmp,2);
	if (tm->tm_sec < 10) {
		sprintf(tmp, "0%d", tm->tm_sec);
	} else {
		sprintf(tmp, "%d", tm->tm_sec);
	}
	strncat(filename,tmp,2);
	strncat(filename,".jpg", 4);
	return 0;
}

// main 函数
int main (int argc, char **argv) {
	char rbuf[1024];
	char request[1024] = {};
	int nbytes = -1;
	int datlen = 0;
	int cfd = -1;
	char filename[18] = {};
	
	//连接服务器
	cfd = connect_server("192.168.1.198", 33);
	if (cfd == -1) {
		printf("connect to server failed.\n");
		return -1;
	}
	// 构建一个请求，获取视频流
	mkrequest(request, 1023, "/videostream.cgi?stream=1", "192.168.1.198:33");
	// 向服务器发送请求
	nbytes = send(cfd, request, strlen(request), 0);
	if (nbytes < 0) {
		printf("Send error.\n");
		return -1;
	}

	//读取http的响应头，以一个空行结束
	bzero(rbuf, 1024);
	nbytes = read_header(cfd, rbuf, 1024);
	rbuf[nbytes] = '\0';
	// printf("%s\n", rbuf);
	//create_control_thread();
	//读取服务器发送来的数据头 以一个空行结束
	while(1) {
		bzero(rbuf, 1024);
		nbytes = read_header(cfd, rbuf, 1024);
		rbuf[nbytes] = '\0';
		// 解析数据头得到数据长度  eg. Content-Length: 25350
		datlen = parse_content_length(rbuf);
		printf("%d\n", datlen);
		mkfilename(filename,18);
		// 取读数据，存储到文件中
		int len = read_data(cfd, filename, datlen);
		printf("while(1) : %d\n", len);
		sleep(1);
	}
	close(cfd);
	return 0;
}





























